package dataaccess;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import model.User;




public class ContatoDao {
 
   // a conexão com o banco de dados
   private Connection connection;
 
   public ContatoDao() {
     this.connection = new ConnectionFactory().getConnection();
   }
   
   public void adiciona(User contato) {
	     String sql = "insert into contatos" +
	             "(nome,email, login, password, birthday, rg, cpf)" +
	             " values (?,?,?,?,?,?,?)";
	 
	     try {
	         // prepared statement para inserção
	         PreparedStatement stmt = connection.prepareStatement(sql);
	 
	         // seta os valores
	         stmt.setString(1,contato.getName());
	         stmt.setString(2,contato.getEmail());
	         stmt.setString(3,contato.getLogin());
	         stmt.setString(4,contato.getPassword());
	         stmt.setDate(5, new Date(
	                 contato.getBirthday().getTimeInMillis()));
	         stmt.setString(6,contato.getRg());
	         stmt.setString(7,contato.getCpf());
	 
	         // executa
	         stmt.execute();
	         stmt.close();
	     } catch (SQLException e) {
	         throw new RuntimeException(e);
	     }
	 }
   
   public User getLista(String login, String password) {
	     try {
	         PreparedStatement stmt = this.connection.
	                 prepareStatement("select * from contatos where login = ? "
	                 		+ "and password = ?");
	         stmt.setString(1,login);
	         stmt.setString(2,password); 
	         ResultSet rs = stmt.executeQuery();
	         
	         while (rs.next()) {
	             // criando o objeto Contato
	             User contato = new User();
	             contato.setId(rs.getString("id"));
	             contato.setName(rs.getString("nome"));
	             contato.setEmail(rs.getString("email"));
	             contato.setLogin(rs.getString("login"));
	             contato.setPassword(rs.getString("password"));
	             contato.setRg(rs.getString("rg"));
	             contato.setCpf(rs.getString("cpf"));
	             
	 
	             // montando a data através do Calendar
	             Calendar data = Calendar.getInstance();
	             data.setTime(rs.getDate("birthday"));
	             contato.setBirthday(data);
	 
	             // adicionando o objeto à lista
	             rs.close();
		         stmt.close();
	             return contato;
	         }
	         rs.close();
	         stmt.close();
	         return null;
	     } catch (SQLException e) {
	         throw new RuntimeException(e);
	     }
	 }
 
 }